from pickle import GLOBAL

from flask import Flask, jsonify, request, send_from_directory
try:
    from flask_cors import CORS
    cors_available = True
except ImportError:
    cors_available = False
import os
from YiXinGame import Game

app = Flask(__name__)
if cors_available:
    CORS(app)  # 添加 CORS 支持
else:
    # 添加一个简单的 CORS 处理装饰器
    def add_cors_headers(response):
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
        return response

    app.after_request(add_cors_headers)

game_instance = Game()
orders = ''

# 静态文件路由
@app.route('/')
@app.route('/gobang')
def index():
    """提供主页"""
    return send_from_directory('.', 'index.html')

@app.route('/<path:path>')
def static_files(path):
    """提供其他静态文件"""
    return send_from_directory('.', path)

@app.route('/api/move', methods=['POST'])
def make_move():
    """处理AI下棋请求"""
    try:
        global orders
        data = request.json
        last_human_move = data.get('lastHumanMove', None)
        ai_first = data.get('aiFirst', False)  # 获取AI是否先手的参数
        if last_human_move:
            orders += game_instance.pos_to_order(last_human_move)
        if ai_first:
            # 调用AI计算下一步
            next_move = game_instance.play(orders)
            orders += next_move
        else:
            next_move = game_instance.play(orders,1)
            orders += next_move
        # game_instance.print_board()
        return jsonify({
            'success': True,
            'move': next_move
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/restart', methods=['POST'])
def restart_game():
    """重启游戏"""
    try:
        global orders
        game_instance.yixin.restart()
        game_instance.order = ''
        orders = ''
        game_instance.winner = 0
        return jsonify({'success': True})
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)